from django.forms.models import model_to_dict
import random
import datetime
from decimal import Decimal

# 订单信息模型转字典
def order_info_to_dict(order_info):
    order = model_to_dict(order_info)
    order["status"] = {
        "code": order_info.status,
        "message": order_info.get_status_display(),
    }
    order["account"] = {
        "account_id": order_info.account.account_id,
        "username": order_info.account.username,
        "balance": str(order_info.account.balance),
        "phone": order_info.account.phone,
    }
    order["create_time"] = order_info.create_time.strftime("%Y-%m-%d %H:%M:%S")
    order["update_time"] = order_info.update_time.strftime("%Y-%m-%d %H:%M:%S")
    order["order_id"] = order_info.order_id
    return order





def generate_random_str():
    # 固定前缀
    prefix = "WZ"
    # 获取当前日期，格式为YYYYMMDD
    current_date = datetime.datetime.now().strftime("%Y%m%d")
    # 获取当前时间，格式为HHMMSS
    current_time = datetime.datetime.now().strftime("%H%M%S")
    # 生成8位随机数字
    random_numbers = ''.join(str(random.randint(0, 9)) for _ in range(8))
    # 组合所有部分
    result = f"{prefix}{current_date}{current_time}{random_numbers}"
    return result


# 更新账号余额
def update_account_balance(account, amount, is_add=True):
    if is_add:
        account.balance += Decimal(amount)
    else:
        account.balance -= Decimal(amount)
    account.save()
